
import cv2 as cv
from PIL import Image
from pdf417decoder import PDF417Decoder
from pylibdmtx.pylibdmtx import decode
from pyzbar.pyzbar import decode

from config.ServerApp import app
from utils.ImgUtils import *

from utils.DataUtil import build_classfy_obj


def classfy_by_qrcode(file_path:str):
    '''
    二维码分类
    '''
    #普通二维码，条形码，收付款码检测
    common_res,qr_text = normal_qr_code_check(file_path)
    if common_res is not None and len(common_res) > 0:
        return common_res,qr_text
    
    # # pdf_471类型二维码
    # pdf_471_res = pdf_471_check(file_path)
    # if pdf_471_res is not None and len(pdf_471_res) > 0:
    #     return pdf_471_res

    # # data matrix 类型二维码
    # data_matrix_res = data_matrix_check(file_path)
    # if data_matrix_res is not None and len(data_matrix_res) > 0:
    #     return data_matrix_res

    return [],[]


def normal_qr_code_check(file_path):
    """
    普通得二维码检测（二维码，条形码）
    """
    qr_text = []
    qr_classfy_list = []
    repeat_list=[]
    qrcode_result = extract_qrcode(file_path)
    for qrcode_info in qrcode_result:
        code_type = qrcode_info["code_type"]
        code_url = qrcode_info["code_url"]
        if(code_type=='条形码'):
            if('条形码' in repeat_list):continue
            qr_classfy_list.append(build_classfy_obj("二维条形码","条形码",1.0))
            repeat_list.append('条形码')
            qr_text.append(qrcode_info["code_url"])
        if(code_type=='二维码'):
            if('二维码' in repeat_list):continue
            qr_classfy_list.append(build_classfy_obj("二维条形码","二维码",1.0))
            repeat_list.append('二维码')
            qr_text.append(qrcode_info["code_url"])
        # 收付款码
        if('pay' in code_url  or 'alipay' in code_url):
            if('收付款码' in repeat_list):continue
            qr_classfy_list.append(build_classfy_obj("二维条形码","收付款码",1.0))
            repeat_list.append('收付款码')
            qr_text.append(qrcode_info["code_url"])
    return qr_classfy_list,qr_text

def pdf_471_check(filePath):
    '''
    pdf_471 类型二维码检测
    '''
    qr_classfy_list = []
    try:
        # 加载包含PDF417条码的图像
        image = Image.open(filePath)
        if image is None:return qr_classfy_list
        # 创建PDF417解码器实例
        decoder = PDF417Decoder(input_image=image)
        # 解码图像中的PDF417条码
        barcodes = decoder.decode()

        # 打印解码结果
        if barcodes:
            qr_classfy_list.append(build_classfy_obj("二维条形码","PDF_471",1.0))
            return qr_classfy_list
    except Exception as e:
        raise e


def data_matrix_check(filePath):
    """
    Data Matrix 类型二维码检测 
    """
    qr_classfy_list = []
    # 打开包含Data Matrix码的图像文件
    image = Image.open(filePath)
    if image is None:return qr_classfy_list
    # 解析图像中的Data Matrix码
    decoded_objects = decode(image)
    if not decoded_objects:
        # 灰度处理再尝试
        image = image.convert("L")
        decoded_objects = decode(image)

    # 遍历解析结果
    if decoded_objects:
        qr_classfy_list.append(build_classfy_obj("二维条形码","Data Matrix",1.0))
    return qr_classfy_list



def extract_qrcode(file_path:str):
    data_res = []
    try:
        # img = cv.imread(file_path, cv.IMREAD_GRAYSCALE)
        img = preprocess_image(file_path)
        if img is None:
            return data_res

        texts = decode(img)
        # if len(texts) == 0:
        #     # 对比度增强
        #     img = cv.convertScaleAbs(img, alpha=1.5, beta=0)
        #     texts = decode(img)
        #
        # if len(texts) == 0:
        #     # canny 检测正方体边缘
        #     edges = cv.Canny(img, 100, 200)
        #
        #     contours, _ =cv.findContours(edges, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
        #     for contour in contours:
        #         # 计算轮廓的近似多边形和边界框
        #         perimeter = cv.arcLength(contour, True)
        #         approx = cv.approxPolyDP(contour, 0.04 * perimeter, True)
        #         if len(approx) == 4:
        #             # 获取边界框的坐标
        #             x, y, w, h = cv.boundingRect(approx)
        #             # 过滤大小小于 32X32的
        #             if w * h < 32 * 32:
        #                 continue
        #             # 绘制边界框
        #             cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        #             # 获取边界框内的图像
        #             cropped_img = img[y:y + h, x:x + w]
        #             texts = decode(cropped_img)
        #             if len(texts) > 0:
        #                 break


        if len(texts) == 0:
            return data_res
        for text in texts:
            type = str()
            if text.type == 'QRCODE':
                type = "二维码"
            else:
                type = "条形码"
            qrcode_info = {'code_type':type,'code_url':text.data.decode("utf-8")}
            data_res.append(qrcode_info)
        return data_res
    except Exception as e:
        app.ctx.logger.error(f"二维码分类失败path：{file_path},error:{str(e)}")
        return data_res

# if __name__ == '__main__':
#     本地验证码
#     网站验证码
#     filePath = "C:/Users/lhx/Desktop/demo/classfy/16.jpg"
    # filePath = r"D:\download\2025-02-24\a485c0436a42cc7bcb9bd4c125e14e01-44.jpg"
    # filePath = r"D:\download\2025-02-24\a485c0436a42cc7bcb9bd4c125e14e01.jpg"
    # filePath = r"D:\download\2025-02-24\20250225133432.jpg"
    # filePath = "C:/Users/lhx/Desktop/demo/classfy/datamatrix3.png"
    # print(pdf_471_check(filePath,[]))
    # print(classfy_by_qrcode(filePath))



